package com.promise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.promise.controller.result.WarningResult;
import com.promise.pojo.Warning;
import com.promise.service.WarningServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/warnings")
public class WarningController {
    @Autowired
    private WarningServiceImpl warningService;

    /**
     * 分页查询记录
     *
     * @param currentPage 当前页码
     * @param pageSize    页面数据条数
     * @param searchData  搜索条件
     * @return WarningResult 分页查询结果
     */
    @PostMapping("/{currentPage}/{pageSize}")
    @ResponseBody
    public WarningResult getWarningByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,
                                          @RequestBody Warning searchData) {
        // 查询条件
        LambdaQueryWrapper<Warning> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(searchData.getWarningDate()),
                        Warning::getWarningDate, searchData.getWarningDate())
                .eq(!StringUtils.isEmpty(searchData.getSeverity()),
                        Warning::getSeverity, searchData.getSeverity())
                .eq(!StringUtils.isEmpty(searchData.getWatchName()),
                        Warning::getWatchName, searchData.getWatchName());

        IPage<Warning> iPage = new Page<>(currentPage, pageSize);
        IPage<Warning> page = warningService.page(iPage, queryWrapper);
        Integer code = page.getRecords() != null ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = page.getRecords() != null ? "查询成功" : "查询失败";
        Map<String, Object> data = new HashMap<>();
        data.put("pages", page.getPages());
        data.put("currentPage", page.getCurrent());
        data.put("pageSize", page.getSize());
        data.put("warnings", page.getRecords());
        data.put("total", page.getTotal());
        return new WarningResult(code, data, msg);
    }

    /**
     * 根据warningId删除
     *
     * @param warningId id
     * @return WarningResult
     */
    @DeleteMapping("delete/{warningId}")
    @ResponseBody
    public WarningResult delete(@PathVariable Integer warningId) {
        boolean flag = warningService.removeById(warningId);
        Integer code = flag ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = flag ? "删除成功" : "删除失败";
        return new WarningResult(code, flag, msg);
    }


    /**
     * 增加警告记录
     *
     * @param warning 警告对象
     * @return WarningResult 增加结果
     */
    @PostMapping("/add")
    @ResponseBody
    public WarningResult addWarning(@RequestBody Warning warning) {
        try {
            boolean isSaved = warningService.save(warning);
            Integer code = isSaved ? Code.SUCCESS_CODE : Code.ERROR_CODE;
            String msg = isSaved ? "增加成功" : "增加失败";
            Map<String, Object> data = new HashMap<>();
            if (isSaved) {
                data.put("warning", warning);
            }
            return new WarningResult(code, data, msg);
        } catch (Exception e) {
            // 处理异常，记录日志等
            Map<String, Object> data = new HashMap<>();
            data.put("error", "系统异常，增加失败");
            return new WarningResult(Code.ERROR_CODE, data, "系统异常，增加失败");
        }
    }


    /**
     * 更新警告信息
     *
     * @param warningId 警告ID
     * @param warningData 更新的警告数据
     * @return WarningResult 更新结果
     */
    @PutMapping("update/{warningId}")
    @ResponseBody
    public WarningResult updateWarning(@PathVariable Integer warningId, @RequestBody Warning warningData) {
        try {
            // 检查警告ID是否在请求体中
            if (warningData.getWarningId() == null || !warningData.getWarningId().equals(warningId)) {
                return new WarningResult(Code.ERROR_CODE, "警告ID不匹配", "更新失败");
            }

            // 调用警告服务的更新方法
            boolean isUpdated = warningService.updateById(warningData);

            // 根据更新结果设置返回状态码和消息
            Integer code = isUpdated ? Code.SUCCESS_CODE : Code.ERROR_CODE;
            String msg = isUpdated ? "更新成功" : "更新失败";

            // 返回更新结果
            return new WarningResult(code, isUpdated, msg);
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
            return new WarningResult(Code.ERROR_CODE, e.getMessage(), "更新失败");
        }
    }
}
